import {Dispatch, useCallback, useEffect, useState} from "react";
import {message} from "antd";
import {IComponent, IComponentType} from "@bastet/widgets";
import {getMaterial, updateMaterial} from "../services";
import type { IMaterial } from "../services";
import { testSceneWidthLocalWidget } from "./useWidget";
import { useSyncCallback } from "./useSyncCallback";

type IGetMaterial = (value: any, debug?: boolean) => any;
export function useMaterial ():[ IMaterial| undefined, IGetMaterial, Dispatch<any>] {
  const [ material, setMaterial ] = useState<IMaterial>()

  const getMaterialById = (id: string, debug?: boolean) => {
    if (!id) Promise.resolve([]);
    return getMaterial(id).then(async ({ code, data }) => {
      console.log({ code, data })
      /**
       * 请求下来的 material
       */
      if (code === 200 && data) {
        if (debug && data.widgets?.length) {
          data.widgets = await testSceneWidthLocalWidget(data.widgets)
        }
        setMaterial(data)
      }
      return data
    })
  }

  const onUpdateMaterial = (widgets: IComponent[])=> {
    console.log('onUpdateMaterial: => ', material)
    if (material) {
      return updateMaterial({ ...material, widgets }).then(({ code, data, msg }) => {
        if (code === 200) {
          message.info(msg)
          setMaterial(data)
        }
      })
    }
  }

  return [ material, getMaterialById, onUpdateMaterial ]
}
